me=
	serverUrlPre:'http://qinjq.0fees.net/index.php?s='
	#上次获取IP时间
	lastGetIPTime:0
	#两次获取IP的间隔时间
	getIpInterval:60*1000
	#当前已有线程数
	threadCnt:0
	#被检测的IP
	ips:[]
	#id到ipInfo的映射
	ipMap:{}
	#一分钟内的请求
	lastMinute:[]
	#不走代理的域名
	noProxyHost:['qinjq.0fees.net','ip.taobao.com','visitweb.allalla.com']
	sep:'__'
	#检测结果
	result:{}
	#结果数量
	resultCnt:0
	#每30个结果上报一次
	reportCntOnce:30
	#用户检测的url
	checkUrl:['visitweb.sinaapp.com','kojiki.server.ne.jp/etc/pj235.cgi','www.taobao.com']
	#获取IP
	getIp:->
		if +new Date()-me.lastGetIPTime<me.getIpInterval
			#1分钟内不再获取
			return off
		me.lastGetIPTime= +new Date()
		ajaxSetting=
			async:off
			data:
				limit:300
			dataType:'json'
			timeout:10*1000
			error:->
				setTimeout me.getIp,me.getIpInterval
			success:(data)->
				if data?.length >1
					#最后一个检测结果不上报，导致无限循环。所以大于1的时候才检测
					me.ips = me.ips.concat data
					for v in data
						me.ipMap[v.agt_id] = v
					me.setProxy()
		$.ajax "#{me.serverUrlPre}Compass/getIP",ajaxSetting
		on
	#设置代理
	setProxy:->
		checkHost = []
		for url in me.checkUrl
			arrUrl = url.split '/'
			checkHost.push arrUrl[0]
		#有些代理IP会返回302状态重定向到其它网页，这里要屏蔽掉其它非检查主机的域名
		proxyFn = """
			function FindProxyForURL(url, host){
				var noProxyHost = #{JSON.stringify(me.noProxyHost)};
				for (var i=noProxyHost.length-1;i>=0;i--){
					if(host==noProxyHost[i]){
						return 'DIRECT';
					}
				}
				var checkHost = #{JSON.stringify(checkHost)};
				var ipMap = #{JSON.stringify(me.ipMap)};
				for(var i=checkHost.length-1;i>=0;i--){
					if(host==checkHost[i]){
						var id = url.split('#{me.sep}')[1];
						if(id){
							var info = ipMap[id];
							if(info){
								return 'PROXY ' + info.agt_ip +':' + info.agt_port;
							}
						}
					}
				}
				return "PROXY localhost:3421";
			}
		"""
		proxyConfig=
			mode:"pac_script"
			pacScript:
				data:proxyFn.trim()
				mandatory:on
		chrome.proxy.settings.set {value:proxyConfig,scope:'regular'},me.createThreads
	#创建线程入口
	createThreads:->
		leftThread = ->
			maxThreadCnt = Math.max($('#maxThread').val(),2)
			maxThreadCnt - me.threadCnt
		canHttp = ->
			now = + new Date()
			lastMinute = me.lastMinute.filter (v)->
				#1分钟内的请求数
				return now - v < 60 * 1000
			return lastMinute.length < 130
		while leftThread() > 0 and canHttp()
			unless me.createThread()
				break
	#创建线程
	createThread:->
		data = me.ips.shift()
		if data
			if me.result[data.agt_id]
				#在结果中,跳过
				return me.createThread()
			me.threadCnt++
			if 0==parseInt(data.agt_rank) or Math.random() <0.3
				me.sinaCheck data
			else
				me.taobaoCheck data
			return on
		off
	#再使用线程
	reUseThread:->
		me.threadCnt--
		me.createThreads()
	#sina节点检测等级
	sinaCheck:(data)->
		ajaxSetting=
			dataType:'json'
			timeout:16*1000
			cache:off
			error:->
				me.jpCheck data
			success:(rank,textStatus)->
				me.setResult data,'rank',rank
				if rank < 4
					me.taobaoCheck data
				else
					me.reUseThread()
		ajax = $.ajax me.makeUrl(data,me.checkUrl[0]),ajaxSetting
	#jp节点检测
	jpCheck:(data)->
		ajaxSetting=
			dataType:'text'
			timeout:16*1000
			cache:off
			error:->
				me.setResult data,'err'
				me.reUseThread()
			success:(text)->
				rank = me.checkJpRank text
				me.setResult data,'rank',rank
				if rank<4
					me.taobaoCheck data
				else
					me.reUseThread()
		$.ajax me.makeUrl(data,me.checkUrl[1]),ajaxSetting
	checkJpRank:(html)->
		ret = 2
		if html.length < 2000
			#网页没有正常显示
			ret = 5
		if html.indexOf('<FONT color="yellow">1</FONT>') > 0
			#prefect代理
			ret = 1
		else if html.indexOf('<FONT color="orange">SPILL</FONT>') > 0 or html.indexOf('Spill your REMOTE_HOST') > 0
			#暴露IP
			ret = 4
		else if html.indexOf('_PROXY') >0
			ret =3
			#alert ret
		ret
	#taobao节点检测
	taobaoCheck:(data)->
		ajaxSetting=
			dataType:'text'
			cache:off
			timeout:16*1000
			error:->
				me.setResult data,'err'
				me.reUseThread()
			success:(text)->
				str = 'success'
				if -1==text.indexOf('淘宝网')
					str='err'
				me.setResult data,str
				me.reUseThread()
		$.ajax me.makeUrl(data,me.checkUrl[2]),ajaxSetting
	#设置检测结果
	setResult:(data,type,rank=on)->
		id = data.agt_id
		unless me.result[id]
			me.result[id] ={}
		me.result[id][type] = rank
		if rank>4 or on==rank
			$('#show').html me.ipMap[id]['agt_ip']
			$('#stastics').html me.resultCnt
			delete me.ipMap[id]
			unless ++me.resultCnt%me.reportCntOnce
				#达到上报数量的时候，直接上报
				me.reportResult()
			if 1==me.threadCnt
				setTimeout ->
					#这里是先setresult再减进程数，所以要延迟执行。不然进程数不对
					unless me.threadCnt
						me.reportResult()
				,1000
	#根据不同的id设置不同的url
	makeUrl:(data,url)->
		"http://#{url}?s=#{me.sep}#{data.agt_id}#{me.sep}"
			
	#上报检测结果
	reportResult:->
		report={}
		cnt = 0
		for id,info of me.result
			if info.rank>3 or info.success or info.err
				report[id] = info
				if ++cnt == me.reportCntOnce
					me.report report
					return on
		me.report report
	#通过ajax发送结果
	report:(report,retry=on)->
		if me.lockReport
			return off
		me.lockReport = on
		#重新获取IP
		reGetIP=(reGet)->
			me.lockReport = off
			unless me.threadCnt
				if !$.isEmptyObject report or reGet
					me.getIp()
				else
					me.reportResult()
		ajaxSetting=
			dataType:'json'
			data:
				report:report
			timeout:16*1000
			error:(xhr,status,error)->
				if retry
					me.report report,off
				else
					reGetIP on
			success:(data)->
				for id of report
					delete me.result[id]
				reGetIP()

		$.ajax "#{me.serverUrlPre}Compass/report",ajaxSetting
		on

	intervalGetIp:->
		if !me.threadCnt and $.isEmptyObject me.result
			me.getIp()
	start:->
		me.getIp()
		#5分钟启动一次
		setInterval me.intervalGetIp,5*60*1000

popHash= '#pop'
startHash='#start'
switch location.hash
	when popHash
		open location.href.replace(popHash,startHash),'compass'
		close()
	when startHash
		#每天重新刷新一下页面，清空内存
		setTimeout location.reload,24*60*60*1000
		me.start()

$('#start').click ->
	me.start()
@me=me


